﻿using Core.FrameWork.Commons.Encrypt;
using Core.FrameWork.Commons.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Email.Core
{
    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <summary>
    /// 
    /// </summary>
    public class SendMailHelper
    {
        private static Dictionary<string, string> _templtes = new Dictionary<string, string>();
        public async Task<bool> SendEmail(MailBodyEntity mailBodyEntity)
        {
            try
            {
                if (mailBodyEntity.Recipients == null || mailBodyEntity.Recipients.Count(t => !string.IsNullOrEmpty(t)) <= 0)
                    return false;
   

                Encoding encoding = Encoding.GetEncoding("utf-8");
                MailMessage mailMessage = new MailMessage
                {
                    From = new MailAddress(Configs.EmailConfig.MailAccount, Configs.EmailConfig.MailSendName, encoding),
                    Subject = mailBodyEntity.Subject,
                    Body = mailBodyEntity.Body,
                    BodyEncoding = encoding,
                    IsBodyHtml = true,
                    Priority = MailPriority.Normal
                };

                mailMessage.To.Add(string.Join(",", mailBodyEntity.Recipients));

                if (mailBodyEntity.Cc != null)
                {
                    mailMessage.CC.Add(string.Join(",", mailBodyEntity.Cc));
                }

                if (mailBodyEntity.Bcc != null)
                {
                    mailMessage.Bcc.Add(string.Join(",", mailBodyEntity.Bcc));
                }
                await BeginSendEmailCore(mailMessage);

                return true;
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        private async Task BeginSendEmailCore(MailMessage param)
        {
            if (param == null)
                return;
            try
            {
                var _smtpClient = new SmtpClient
                {
                    Host = Configs.EmailConfig.MailHost,
                    Port = Configs.EmailConfig.MailPort.ToInt(),
                    EnableSsl = Configs.EmailConfig.MailSSLEnabled,
                    Credentials = new System.Net.NetworkCredential { UserName = Configs.EmailConfig.MailAccount, Password = Configs.EmailConfig.MailPwd },

                };

                await _smtpClient.SendMailAsync(param);
            }
            catch (Exception e)
            {
                string ex = e.ToString();
            }
        }
        public async Task<bool> SendEmailAsync(MailBodyEntity mailBodyEntity)
        {
            return await SendEmail(mailBodyEntity);
        }
        /// <summary>
        /// 发送邮件-替换模板
        /// </summary>
        /// <param name="mailBodyEntity"></param>
        /// <returns></returns>
        public async Task<bool> SendEmailFromTemplateAsync(MailBodyEntity mailBodyEntity)
        {
            string content = await GenerateEmailContentByTemplateName(mailBodyEntity.TemplateName, mailBodyEntity.Parameters);

            mailBodyEntity.Body = content;

            return await SendEmailAsync(mailBodyEntity);
        }
        /// <summary>
        /// 读取模内容
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private async Task<string> GenerateEmailContentByTemplateName(string templateName, Dictionary<string, string> parameters)
        {
            templateName = templateName.Replace(".html", "").ToLower();
            string templateContent = "";
            if (!_templtes.ContainsKey(templateName))
            {
                string fileName = string.Format("{0}/{1}.html", (AppDomain.CurrentDomain.BaseDirectory + Configs.EmailConfig.EmailTemplateFolder.Trim('/')), templateName);
                if (File.Exists(fileName))
                {
                    templateContent = await File.ReadAllTextAsync(fileName);
                    if (!_templtes.ContainsKey(templateName))
                    {
                        _templtes.Add(templateName, templateContent);
                    }
                }
                else
                {
                    throw new FileNotFoundException("邮件模板未找到", fileName);
                }
            }
            else
            {
                templateContent = _templtes[templateName];
            }
            return GenerateEmailContentFromTemplate(templateContent, parameters);
        }
        /// <summary>
        /// 替换模板参数
        /// </summary>
        /// <param name="template"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private string GenerateEmailContentFromTemplate(string template, Dictionary<string, string> parameters)
        {
            StringBuilder emailContentBuilder = new StringBuilder(template);
            if (parameters != null)
            {
                foreach (var item in parameters)
                {
                    emailContentBuilder.Replace("#" + item.Key + "#", item.Value);
                }
            }
            return emailContentBuilder.ToString();
        }

        public void Dispose()
        {

        }
    }

}
